<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 -->
<!-- 
* @desc:修改密码组件
* @fileName:HeaderChangePassword.vue
* @author:zoujunjie
* @date:2022-05-06
!-->
<template>
  <HeaderIconItem
    :icon-url="iconLock"
    tooltip="修改密码"
    @click="onChangePasswordClick"
    class="hover-cursor-pointer"
  ></HeaderIconItem>
  <el-dialog
    title="修改密码"
    :destroy-on-close="true"
    v-model="showChangePasswordDialog"
    width="500px"
    @closed="onDialogClosed"
  >
    <el-result v-if="changeSuccessed" icon="success" title="修改成功">
      <template #extra>
        <el-button type="primary" @click="onDialogClosed()">好的</el-button>
      </template>
    </el-result>
    <el-form
      v-else
      ref="changePasswordForm"
      :model="changePasswordModel"
      :rules="rules"
      label-width="120px"
      status-icon
      size="large"
      label-position="left"
    >
      <el-form-item label="旧密码" prop="old">
        <el-input
          v-model="changePasswordModel.old"
          type="password"
          autocomplete="off"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="new">
        <el-input
          v-model="changePasswordModel.new"
          type="password"
          autocomplete="off"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirm">
        <el-input
          v-model="changePasswordModel.confirm"
          type="password"
          autocomplete="off"
          placeholder="请输入"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer" v-if="changeSuccessed == false">
        <span class="color-error error-text">{{ errorText }}</span>
        <el-button @click="onDialogClosed()">取消</el-button>
        <el-button
          type="primary"
          :loading="isLoading"
          @click="onConfirmClick(changePasswordForm)"
        >
          确定修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import HeaderIconItem from "./HeaderIconItem.vue";
import iconLock from "@/assets/img/layout/header/icon-lock.png";
import type { FormInstance } from "element-plus";
import { ref, reactive } from "vue";
import { changePassword, ChangePasswordModel } from "@/services/user";
import { isAdminRoute } from "@/services/common/context";
import { checkPassword } from "@/services/common/tool";
import { useRoute } from "vue-router";

const route = useRoute();
const changeSuccessed = ref(false);
const showChangePasswordDialog = ref(false);
const changePasswordForm = ref<FormInstance>();
const changePasswordModel = ref<ChangePasswordModel>({
  old: "",
  new: "",
  confirm: "",
});
const errorText = ref("");
const isLoading = ref(false);

const validatePassword = (rule: any, value: any, callback: any) => {
  if (!checkPassword(value)) {
    callback(new Error("必须同时包含英文大小写、数字和特殊符号"));
  } else {
    callback();
  }
};

const validateNewPassword = (rule: any, value: any, callback: any) => {
  if (value === changePasswordModel.value.old) {
    callback(new Error("新密码不能和旧密码一样"));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== changePasswordModel.value.new) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};

const rules = reactive({
  old: [
    { required: true, message: "还没有输入旧密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度为6-20位", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" },
  ],
  new: [
    { required: true, message: "还没有输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度为6-20位", trigger: "blur" },
    {
      validator: validateNewPassword,
      trigger: "blur",
    },
    { validator: validatePassword, trigger: "blur" },
  ],
  confirm: [
    { required: true, message: "还没有确认新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度为6-20位", trigger: "blur" },
    {
      validator: validateConfirmPassword,
      trigger: "blur",
    },
  ],
});

const onChangePasswordClick = (): void => {
  showChangePasswordDialog.value = true;
};

const onConfirmClick = async (formEl: FormInstance | undefined) => {
  errorText.value = "";
  if (!formEl) {
    isLoading.value = false;
    return;
  }
  isLoading.value = true;
  await formEl.validate((valid, fields) => {
    if (valid) {
      changePassword(changePasswordModel.value, isAdminRoute(route))
        .then((r) => {
          changeSuccessed.value = true;
          isLoading.value = false;
        })
        .catch((err) => {
          console.log("catch", err);
          errorText.value = err.data;
          isLoading.value = false;
        });
    } else {
      isLoading.value = false;
    }
  });
};

const onDialogClosed = (): void => {
  showChangePasswordDialog.value = false;
  changeSuccessed.value = false;
  changePasswordModel.value.old = "";
  changePasswordModel.value.new = "";
  changePasswordModel.value.confirm = "";
  errorText.value = "";
};
</script>

<style lang="scss" scoped>
.dialog-footer .error-text {
  margin-right: 10px;
}
</style>
